#include "../cpp-httplib/httplib.h"
#include "oj_control.hpp"
#include <regex>

using namespace httplib;
using namespace ns_control;
static Control *ctrl_ptr = nullptr;

void Usage(std::string proc)
{
    std::cout << "Usage\r\t" << proc << " port" << std::endl;
}

void Recovery(int signo)
{
    ctrl_ptr->RecoveryMachine();
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(1);
    }

    signal(SIGQUIT, Recovery);
    // 用户请求的路由功能5
    httplib::Server svr;
    Control ctrl;
    ctrl_ptr = &ctrl;
    svr.set_base_dir("./wwwroot");

    // 1. 获取全部题目列表
    svr.Get("/all_questions", [&ctrl](const Request &req, Response &resp)
            {
                std::string html;
                ctrl.AllQuestions(&html);
                resp.set_content(html, "text/html, charset=utf-8"); });

    // 2. 根据题目编号获取题目内容
    svr.Get(R"(/question/(\d+))", [&ctrl](const Request &req, Response &resp)
            {
                // \d+ 为正则匹配, 可以匹配任何长度的数字
                // R"()" 为C++新特性, 可以保持括号内字符串的原貌
                // req.matches[1] 获取到正则匹配的数字
                std::string number = req.matches[1];
                std::string html;
                ctrl.OneQuestion(number, &html);
                resp.set_content(html, "text/html, charset=utf-8"); });

    // 3. 根据提交的代码进行判题
    svr.Post(R"(/judge/(\d+))", [&ctrl](const Request &req, Response &resp)
             { 
                std::string number = req.matches[1];
                std::string in_json = req.body;
                std::string out_json;
                ctrl.Judge(number, in_json, &out_json);
                resp.set_content(out_json, "application/json; charset=utf-8"); });

    svr.listen("0.0.0.0", atoi(argv[1]));
    return 0;
}